
package com.lzx.iteam.contactssearch.conversion;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import com.lzx.iteam.DialerApp;
import com.lzx.iteam.contactssearch.ContactsDBReader;
import com.lzx.iteam.util.PreferenceUtil;
import com.lzx.iteam.util.WeakAsyncTask;

import java.util.Timer;
import java.util.TimerTask;

public class NameConvertService extends Service {

    public static final String ACTION_START = "com.lzx.iteam.contactssearch.NameConvertService.START";

    private static final String TAG = "NameConvertService";

    private static long AUTO_CLOSE_TIME = 60 * 1000;

    private PersistWorker mPersister;

    private PersisitTask mPersistTask;

    private boolean mLastRequestFlag = false;

    private Timer mIdleClosedTimer;

    private boolean mTimerScheduledFlag = false;
    
    private boolean mServiceStartUp = false;

    private static class PersisitTask extends
            WeakAsyncTask<Void, Void, Integer, NameConvertService> {

        private static final int UNCHANGED = 0;

        private static final int SUCCESSFUL = 1;

        private static final int FAILED = 2;

        public PersisitTask(NameConvertService target) {
            super(target);
        }

        protected Integer doInBackground(NameConvertService target, Void... params) {
            boolean ok = target.doContactsChanges();
            return ok ? SUCCESSFUL : FAILED;
        }

        protected void onPostExecute(NameConvertService target, Integer result) {
            target.onFinishedWork(result);
        }
    }

    public void onFinishedWork(int result) {
        // AsyncTask only can be used for once, and said that creating several
        // times does not cause GC problems
        mPersistTask = null;

        if (mLastRequestFlag) {
            mLastRequestFlag = false;
            doStartAction();
        } else {
            scheduleAutoClose();
        }
        /*boolean sync = mPreferenceUtil.get(PreferenceUtil.SYNC_UP_OVER, Boolean.class);
        mPreferenceUtil.save(PreferenceUtil.SYNC_UP_OVER, !sync);*/
    }

    private boolean doContactsChanges() {
//        contactsdbreader.resetallcontactsnumber(this);
        if(ContactsDBReader.mGroupList == null){
            ContactsDBReader.getGroupHash(this.getContentResolver());
            ContactsDBReader.getNoGroupsSet(this);
        }

        //服务异常终止
        if (mPersister == null) {
           return true; 
        }
        mPersister.getChangesList(mServiceStartUp);
        if (mServiceStartUp) {
            mServiceStartUp = false;
        }
        return true;
    }

    private void scheduleAutoClose() {
        // I will check if it creates duplicate Timer
        if (mTimerScheduledFlag && mIdleClosedTimer != null) {
            mIdleClosedTimer.cancel();
        }
        mIdleClosedTimer = new Timer();

        // set idle closed time
        mIdleClosedTimer.schedule(new TimerTask() {

            @Override
            public void run() {
                if (mPersistTask == null) {
                    // if no work are doing now, close the service
                    stopSelf();
                } else {
                    mIdleClosedTimer.cancel();
                }

                mTimerScheduledFlag = false;
            }
        }, AUTO_CLOSE_TIME);
        mTimerScheduledFlag = true;
    }

    private DialerApp mDialerApp;
    
    private PreferenceUtil mPreferenceUtil;
    
    private PinyinSearch mPinyinSearch;
    
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent == null) {
            stopSelf();
            return START_NOT_STICKY;
        }
        mDialerApp = (DialerApp) getApplication();
        mPreferenceUtil = PreferenceUtil.getInstance(this);
        mPinyinSearch = PinyinSearch.getInstance(this);

        String act = intent.getAction();

        // ONLY accepts defining Intent and start to work.
        if (ACTION_START.equals(act)) {
            if (mPersistTask == null) {
                doStartAction();
            } else {
                mLastRequestFlag = true;
                mPinyinSearch.setPersistInterrupted(true);
            }
        } else {
            // directly close if service is idle
            if (mPersistTask == null) {
                scheduleAutoClose();
            }
        }

        return START_NOT_STICKY;
    }

    private void doStartAction() {
        mPinyinSearch.setPersistInterrupted(false);
        mPersistTask = new PersisitTask(this);
        mPersistTask.execute();
    }

    @Override
    public void onCreate() {
        super.onCreate();

//        mDigitizer = new DigitizeWorker();
        mServiceStartUp = true;
        mPersister = PersistWorker.getInstance(this);
    }

    @Override
    public void onDestroy() {
        if(mIdleClosedTimer != null){
            mIdleClosedTimer.cancel();
        }

        if(mPersistTask != null){
            mPersistTask.cancel(true);
        }
        super.onDestroy();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}
